﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;

namespace LocalStorageOfBooks
{
    public partial class MainPage : PhoneApplicationPage
    {
        private const string Connection = "isostore:/bookDB.sdf";
        
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            DataContext db = new BooksDataContext(Connection);
            if (!db.DatabaseExists())
            {
                db.CreateDatabase();
            }

            CreateBook.Click += CreateBook_Click; 
            ShowData.Click += ShowData_Click; 
        }

        void CreateBook_Click(object sender, RoutedEventArgs e)
        {
            var db = new BooksDataContext(Connection);
           
            AddPublisher(db);
            AddAuthors(db);
            AddBooks(db);
        }

        private static void AddPublisher(BooksDataContext db)
        {
            var pub = new Publisher { PublisherID = "1", Name = "APress", City = "Acton", Url = "http://Apress.com" };
            db.Publishers.InsertOnSubmit(pub);

            db.SubmitChanges(); 
        }

        private static void AddAuthors(BooksDataContext db)
        {
            var auth = new Author {AuthorID = "1", FirstName = "Jesse", LastName = "Liberty"};
            db.Authors.InsertOnSubmit(auth);

            auth = new Author {AuthorID = "2", FirstName = "Paul", LastName = "Betts"};
            db.Authors.InsertOnSubmit(auth);

            auth = new Author {AuthorID = "3", FirstName = "Jeff", LastName = "Blankenburg"};
            db.Authors.InsertOnSubmit(auth);

            db.SubmitChanges(); 
        }

        private static void AddBooks(BooksDataContext db)
        {
            var theBook = new Book
            {
                BookID = "1",
                Author = "2",
                Publisher = "1",
                PublicationDate = DateTime.Now,
                Title = "Programming Reactive Extensions"
            };
            db.Books.InsertOnSubmit(theBook);
            
            theBook = new Book
            {
                BookID = "2",
                Author = "3",
                Publisher = "1",
                PublicationDate = DateTime.Now,
                Title = "Migrating to Windows Phone"
            };
            db.Books.InsertOnSubmit(theBook);

            db.SubmitChanges();
        }

        void ShowData_Click(object sender, RoutedEventArgs e)
        {
            var db = new BooksDataContext(Connection); 
            
            var query = from book in db.Books orderby book.Title select book; 
            List<Book> books = query.ToList(); 
            BooksLB.ItemsSource = books; 
        }

    }
}